from datetime import datetime

import requests
from sqlalchemy.ext.asyncio import AsyncSession

from module_admin.dao.business.sms_record_dao import SmsRecordDao
from module_admin.entity.do.business.sms_record_do import SmsRecord
from module_admin.entity.vo.business.sms_record_vo import SmsRecordPageQueryModel
from module_admin.entity.vo.common_vo import CrudResponseModel
import xml.etree.ElementTree as ET


class SmsRecordService:
    """
    短信记录模块业务层
    """

    @classmethod
    async def get_sms_record_list_services(cls, db: AsyncSession, query_object: SmsRecordPageQueryModel,
                                           is_page: bool = False):
        """
        获取短信记录信息列表
        :param db: 数据库连接对象
        :param query_object: 查询对象
        :param is_page: 是否分页
        :return: 短信记录信息列表
        """
        sms_record_list_result = await SmsRecordDao.get_sms_record_dao(db, query_object, is_page)

        return sms_record_list_result

    @classmethod
    async def add_sms_record_services(cls, query_db: AsyncSession, page_object: SmsRecord):
        """
        新增短信记录信息
        :param query_db: 数据库连接对象
        :param page_object: 新增对象
        :return: 新增结果
        """
        try:
            await SmsRecordDao.add_sms_record_dao(query_db, page_object)
            await query_db.commit()
            # print('新增成功')
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            print(f'新增失败: {e}')
            return CrudResponseModel(is_success=False, message='新增失败')

    @classmethod
    async def send_sms(cls, app_code: str, content: str, phone: str):
        """
        发送短信
        :param app_code: 应用编码
        :param content: 短信内容
        :param phone: 手机号
        :return: 发送结果
        """
        url = 'http://dx.zjsjy.gov/SendSmsService/SmpWebService.asmx'
        payload = (('<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '
                    'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" '
                    'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n  <soap:Body>\r\n    <SendSms '
                    'xmlns=\"http://tempuri.org/\">\r\n      <content>') + content + ('</content>\r\n      '
                                                                                      '<addresseeTel>') + phone +
                   '</addresseeTel>\r\n      <sendTime>' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                   '</sendTime>\r\n      <userAccount>admin</userAccount>\r\n      <password>123456</password>\r\n    '
                   '  <appCode>' + app_code + '</appCode>\r\n    </SendSms>\r\n  </soap:Body>\r\n</soap:Envelope>')
        headers = {
            'Content-Type': 'text/xml; charset=utf-8',
            'SOAPAction': 'http://tempuri.org/SendSms'
        }

        response = requests.request('POST', url, headers=headers, data=payload.encode('utf-8'))

        root = ET.fromstring(response.text)
        namespace = {
            'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
            'ns': 'http://tempuri.org/'
        }

        result = root.find('.//ns:SendSmsResult', namespace)
        # 提取result的文本内容
        if result is not None:
            result_text = result.text
            # 假设SendSmsResult的文本内容是一个JSON字符串
            import json
            result_json = json.loads(result_text)
            msgs = result_json.get('msgs')
            status = result_json.get('status')
            print(f'Msgs: {msgs}, Status: {status}')
            return {
                'message': msgs,
                'status': status
            }
        else:
            print('SendSmsResult element not found')
            return None
